package com.thx.common.util;

import java.util.Date;
import java.util.Random;

/**
 * 生成随机字符串.
 *
 * @author balance
 */
public class RandomTextUtil {

  /**
   * 方便识别的数字字母组合.
   */
  private static char[] ALPHA_NUMERIC = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'M', 'N',
      'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'X', 'Y', 'Z', '2', '3', '4', '5', '6', '7', '8', '9', '1',
      '0'};

  /**
   * 运算符.
   */
  private static final String[] OPERATORS_CHAR = {"+", "-", "*", "/", "加", "减", "乘", "除"};

  /**
   * 中文数字.
   */
  private static final String[] CHINA_NUMERIC = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌",
      "玖", "拾"};

  public static enum Type {
    /**
     * 数字验证码，如：8768.
     */
    numeric,

    /**
     * 字母数字组合验证码， 如：3D8H.
     */
    alphanumeric,

    /**
     * 算术题验证码，如：?+3=5.
     */
    arithmetic
  }

  /**
   * 创建数字随机数.
   */
  public static String[] createNumericRandomText(int length) {
    length = length < 4 ? 4 : length;
    String captcha = "";

    long seed = new Date().getTime();
    Random random = new Random(seed);
    // 随机生成数
    for (int i = 0; i < length; i++) {
      int str = random.nextInt(10);
      captcha = String.format("%s%d", captcha, str);
    }
    return new String[] {captcha, captcha};
  }

  /**
   * 创建字母数字随机数.
   */
  public static String[] createAlphaNumericRandomText(int length) {
    length = length < 4 ? 4 : length;
    String captcha = "";

    long seed = new Date().getTime();
    Random random = new Random(seed);
    // 随机生成数
    for (int i = 0; i < length; i++) {
      int str = random.nextInt(ALPHA_NUMERIC.length);
      captcha = String.format("%s%s", captcha, ALPHA_NUMERIC[str]);
    }

    return new String[] {captcha, captcha};
  }

  /**
   * 算术题验证码.
   */
  public static String[] createArithmeticRandomText(int length) {
    // TODO Auto-generated method stub
    return null;
  }

  /**
   * 创建随机字符串.
   *
   * @param type 类型,可以是 numeric, alphanumeric, arithmetic 其中一种
   * @param length 长度
   * @return 满足要求的随机字符串
   */
  public static String[] createRandomText(Type type, int length) {
    switch (type) {
      case numeric:
        return createNumericRandomText(length);
      case alphanumeric:
        return createAlphaNumericRandomText(length);
      case arithmetic:
        return createArithmeticRandomText(length);
      default:
        break;
    }
    return createNumericRandomText(length);
  }

  /**
   * 测试 main.
   */
  public static void main(String[] args) {

    for (int i = 0; i < 10; i++) {
      String[] code = RandomTextUtil.createRandomText(Type.alphanumeric, 5);

      System.out.println(String.format("%s %s", code[0], code[1]));
    }
  }
}
